#include "matrix.h"

Matrix::Matrix(size_t rows, size_t cols)
{
    this->refcount = new int[1]{1};
    this->rows = rows;
    this->cols = cols;
    this->data = nullptr;
    create(rows, cols);
    std::cout << "constructor" << std::endl;
}

Matrix::~Matrix()
{
    if(*(this->refcount) > 1)
    {
        *(this->refcount) -= 1;
        std::cout << "deconstrctior -refcount = " << *(this->refcount) << std::endl;
    }
    else
    {
        delete []data;
        delete refcount;
        std::cout << "deconstructor" << std::endl;
    }
}

Matrix::Matrix(const Matrix & m)
{
    this->cols = m.cols;
    this->rows = m.rows;
    this->data = m.data;
    this->refcount = m.refcount;
    *(this->refcount) += 1;
    std::cout << "copy constructor+refcount = " << *(this->refcount) << std::endl;
}

Matrix Matrix::operator+(const Matrix & a)
{
    assert(this->rows == a.rows && this->cols == a.cols);
    Matrix tmp(a.rows, a.cols);
    for(int i = 0; i < rows * cols; i++)
    {
        (tmp.data)[i] = (this->data)[i] + (a.data)[i];
    }
    return tmp;
}

Matrix Matrix::operator*(const float b)
{
    Matrix tmp(this->rows, this->cols);
    for(int i = 0; i < rows * cols; i++)
    {
        (tmp.data)[i] = (this->data)[i] * b;
    }
    return tmp;
}

void Matrix::create(size_t rows, size_t cols)
{
    this->data = new float[rows * cols];
    // float array[rows * cols]={0}; 
    for(size_t i = 0; i < rows * cols; i++)
    {
        (this->data)[i] = i *1.;
    }
    // this->data = array;
}

Matrix & Matrix::operator=(const Matrix & a)
{
    this->cols = a.cols;
    this->rows = a.rows;
    this->data = a.data;
    this->refcount = a.refcount;
    *(this->refcount) += 1;
    std::cout << "assignment +refcount = " << *(this->refcount) << std::endl;
    return *this;
}

std::ostream & operator<<(std::ostream & os, const Matrix & ms)
{
    os << ", data = " << static_cast<void*>(ms.data);
    os << " [" << ms.data << "]";
    return os;
}
